﻿using lso_2u_Web应用开发.Models.Database;
using Microsoft.AspNetCore.Http;
/** 此类用于管理Session, 请勿在其他方法中直接操作Session
 * 若需要获取用户信息请使用UserService
 */
namespace lso_2u_Web应用开发.Models
{
    // 非特殊需要, 请勿在其他类中使用UserSessionValues
    public class UserSessionValues
    {
        public const string CAPTCHA_CODE = "captcha_code";

        public const string USER_ID_KEY = "user_id";
        public const string USER_POWER_KEY = "user_power";

        public const string USER_POWER_USER = "user";
        public const string USER_POWER_ADMIN = "admin";
    }

    // 请勿直接使用自定义Key操作Session, 应在为SessionHelper注册后使用
    public class SessionHelper
    {
        static ISession _session;

        public SessionHelper()
        {
        }

        public SessionHelper(ISession session)
        {
            _session = session;
        }

        public void Clear()
        {
            _session.Clear();
        }

        public string CaptchaCode 
        {
            get
            {
                return _session.GetString(UserSessionValues.CAPTCHA_CODE);
            }

            set
            {
                _session.SetString(UserSessionValues.CAPTCHA_CODE, value);
            }
        }

        public string UserPower
        {
            get
            {
                return _session.GetString(UserSessionValues.USER_POWER_KEY);
            }

            set
            {
                _session.SetString(UserSessionValues.USER_POWER_KEY, value);
            }
        }

        public int? UserId
        {
            get
            {
                return _session.GetInt32(UserSessionValues.USER_ID_KEY);
            }

            set
            {
                if (value.HasValue)
                {
                    _session.SetInt32(UserSessionValues.USER_ID_KEY, (int)value);
                }
                else
                {
                    _session.Remove(UserSessionValues.USER_ID_KEY);
                }
            }
        }

        public bool IsLogined
        {
            get
            {
                return UserId.HasValue;
            }
        }

        public void SetLogin(User user)
        {
            if (user == null)
            {
                return;
            }
            this.UserId = user.Id;
            this.UserPower = user.Actor == "admin" ? UserSessionValues.USER_POWER_ADMIN : UserSessionValues.USER_POWER_USER;
        }

        public void SetLogout(User user)
        {
            _session.Clear();
        }
    }
}
